package com.cfpl.interceptor;

import com.cfpl.admin_service.service.AdminService;
import com.cfpl.project_common.context.BaseContext;
import com.cfpl.project_common.enums.CodeEnum;
import com.cfpl.project_common.exception.BusException;
import com.cfpl.project_common.pojo.Admin;
import com.cfpl.project_common.pojo.Permission;
import com.cfpl.project_common.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Jwt登录拦截器   需在接口模块中自定义拦截器配置使用
 */
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    private AdminService adminService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 这里拦截器的作用：
     * Token认证已经在filter中实现，但是在登陆之后，请求没有携带Token也能够被Security的过滤器认证放行。可能是Security中还留存着用户的信息。
     * 这里就再次对Token进行认证，如果Token为空返回异常结果。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("*************解析Token******************");
//        String token = request.getHeader("token");
//        Long adminID = JWTUtil.getUserId(token);
//        log.info("拦截用户:{}",adminID);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentUserId();
        SecurityContextHolder.getContextHolderStrategy().clearContext();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
